//
//  MySessionURLManager.m
//  掌上宏力
//
//  Created by admin on 2017/5/22.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "MySessionManager.h"

NSString *const login_url = @"api/Account/LoginResult";

NSString *const APPid = @"wx66fe0d52a775a301";
NSString *const AppSecret = @"8b89c2620967a41d0cb3ac28e25727ef";

NSString *const entoken_url = @"api/Commn/Encode";
NSString *const token_key = @"token";
NSString *const getToken_url = @"api/Service/GetToken?";



@implementation MySessionManager
singleton_implementation(MySessionManager)

-(AFURLSessionManager *)URLManager{
    if (_URLManager == nil) {
        _URLManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        _URLManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    return _URLManager;
}
//获取token用
-(AFHTTPSessionManager *)HTTPManager{
    if (_HTTPManager == nil) {
        _HTTPManager = [AFHTTPSessionManager manager];
        
        _HTTPManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    return _HTTPManager;
}


-(NSString *)token{
    if (_token == nil) {
        // 获取token
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        
        //从NSUserDefaults中读取上次保存的字符串，并赋给NSString。
        NSString *tokenStr=[defaults stringForKey:token_key];
        if (tokenStr) {
            _token = tokenStr;
        }else{
            NSString *tokenUrl = [NSString stringWithFormat:@"%@%@Appid=%@&AppSecret=%@",HOSPITAL_URL,getToken_url,APPid,AppSecret];
            
            [self.HTTPManager GET:tokenUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                NSString *token = dic[@"Data"][@"AccessToken"];
                // NSLog(@"获取token--->:%@",token);
                //保存到本地文件
                [self saveToken:token];
                _token = token;
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }
    
    return _token;
}
/**
 保存到本地
 */
-(void)saveToken:(NSString *)token{
    //加密
    [self encryptToken:token success:^(NSString *enToken) {
        //通过standardUserDefaults获取共享的NSUserDefaults对象
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        //将用户输入的文本保存到NSUserDefault对象
        [defaults setObject:enToken forKey:token_key];
        //synchronize方法手动将NSUserDefaults对象的改变保存到defaults数据库。
        [defaults synchronize];
    }];
}

/**
 加密token
 */
-(void)encryptToken:(NSString *)token success:(void (^)(NSString *))success{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",HOSPITAL_URL,entoken_url];
    NSDictionary *info = @{@"Estring":token};
    
    NSMutableURLRequest *request = [self createURLRequestWithInfo:info url:url token:nil];
    
    [[self.URLManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"res----> %@---->%@",resultDic,responseObject);
        NSString *enToken = resultDic[@"result"][@"Base64"];
        success(enToken);
    }] resume];
}


-(void)loginWithUSER:(User *)user success:(void (^)(id result))success failure:(void (^)(id result))failure{
    NSString *loginUrl = [NSString stringWithFormat:@"%@%@",HOSPITAL_URL,login_url];
    //    NSLog(@"lognin-Url----%@",loginUrl);
    NSDictionary *userInfo = @{@"username":user.username,@"password":user.password};
    
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:loginUrl parameters:nil error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置body
    NSData *body = [NSJSONSerialization dataWithJSONObject:userInfo options:NSJSONWritingPrettyPrinted error:nil];
    [request setHTTPBody:body];
    
    [[self.URLManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([resultDic[@"Status"] intValue]==1) {
            success(resultDic);
        }else{
            failure(resultDic);
        }
    }] resume];
    
}

-(void)accessCommonServerWithURLStr:(NSString *)url body:(NSDictionary *)dic success:(void (^)(id))success failure:(void (^)(id))failure{
    
    NSMutableURLRequest *request = [self createURLRequestWithInfo:dic url:url token:self.token];
    
    [[self.URLManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"---result%@",resultDic);
        if ([resultDic[@"Status"] intValue]==1) {
            success(resultDic);
        }else{
            failure(resultDic);
        }
    }] resume];
}

-(void)accessNewsServerWithURLStr:(NSString *)url body:(NSDictionary *)dic success:(void (^)(id))success failure:(void (^)(id))failure{
    
    NSMutableURLRequest *request = [self createURLRequestWithInfo:dic url:url token:self.token];
    
    [[self.URLManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(resultDic);
        
    }] resume];
    
}

-(NSMutableURLRequest *)createURLRequestWithInfo:(NSDictionary *)dic url:(NSString *)url token:(NSString *)token{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    if (token) {
        //        [request setValue:[NSString stringWithFormat:@"BasicAuth %@",token] forHTTPHeaderField:@"Authorization"];
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置body参数
    NSData *body = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    [request setHTTPBody:body];
    return request;
}

-(void)accessHXTServerWithURLStr:(NSString *)url success:(void (^)(id))success failure:(void (^)(id))failure{
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    if (self.token) {
        //        [request setValue:[NSString stringWithFormat:@"BasicAuth %@",self.token] forHTTPHeaderField:@"Authorization"];
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [[self.URLManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"服务器返回结果：%@  \n %@",resultDic,request.URL);
        if ([resultDic[@"status"] isEqualToString:@"success"]) {
            success(resultDic);
        }else{
            failure(resultDic);
        }
    }] resume];
    
}

@end
